package com.wrh.draw.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.geojson.FeatureCollection;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author wrh
 */
public class ReadProGeoJson {

    /**
     * 获取省份边界 GeoJson
     *
     * @param adminCode 行政区码（例如湖北：420000）
     * @return GeoJson
     */
    public static FeatureCollection getBoundaryGeoJsonRead(String adminCode) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(getBoundaryGeoJsonStringRead(adminCode), FeatureCollection.class);
    }

    /**
     * 获取省份边界 GeoJson字符串
     *
     * @param adminCode 行政区码（例如湖北：420000）
     * @return String
     */
    public static String getBoundaryGeoJsonStringRead(String adminCode) {
        String filePath = "public/boundary/" + adminCode + ".json";
        InputStream dataStream = ReadProGeoJson.class.getClassLoader().getResourceAsStream(filePath);
        try {
            assert dataStream != null;
            return inputStreamToString(dataStream, StandardCharsets.UTF_8.toString());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                assert dataStream != null;
                dataStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private static String inputStreamToString(InputStream inputStream, String charsetName) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString(charsetName);
    }

}
